package com.rxnetwork.sample.utils.interceptor

import android.content.Context
import android.util.Log
import com.rxnetwork.sample.utils.network.AppNetworkAvailable
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * 缓存拦截器
 */
class AppCacheInterceptor(private val context: Context) : Interceptor {

    init {
        Log.i(TAG, "缓存文件目录:" + context.cacheDir)
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()//获取请求
        if (!AppNetworkAvailable.isNetworkAvailable(context)) {
            request = request.newBuilder()
                    // 缓存策略。
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build()
            Log.d("AppCacheInterceptor", "no network")
        }
        val originalResponse = chain.proceed(request)
        if (AppNetworkAvailable.isNetworkAvailable(context)) {
            val maxAge = 0
            return originalResponse.newBuilder()
                    //这里设置的为0就是说不进行缓存，我们也可以设置缓存时间
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .removeHeader("Pragma")
                    .build()
        } else {
            val maxTime = 5 * 24 * 60 * 60//5天
            return originalResponse.newBuilder()
                    //这里的设置的是我们的没有网络的缓存时间，想设置多少就是多少。
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxTime)
                    .removeHeader("Pragma")
                    .build()
        }
    }

    companion object {

        private val TAG = "AppCacheInterceptor"
    }

}